package com.sky.handler;

import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

import static com.sky.constant.MessageConstant.ALREADY_EXISTS;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler//捕获指定异常
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }
    /**
     *处理SQL异常
     * @param ex 捕获SQL异常
     * @return 返回错误信息
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //获取错误信息
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            //获取用户名
            String[] split = message.split(" ");
            String username = split[2].substring(1, split[2].length() - 1) + ALREADY_EXISTS;
            return Result.error(username);
        }else {
            return Result.error("未知错误");
        }
    }
}
